{
  "cells": [
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "XIyP_0r6zuVc"
      },
      "source": [
        "<!-- Banner Image -->\n",
        "<img src=\"https://uohmivykqgnnbiouffke.supabase.co/storage/v1/object/public/landingpage/brev-xmas-3.png\" width=\"100%\">\n",
        "\n",
        "<!-- Links -->\n",
        "<center>\n",
        "  <a href=\"https://brev.nvidia.com\" style=\"color: #06b6d4;\">Console</a> •\n",
        "  <a href=\"https://developer.nvidia.com/brev\" style=\"color: #06b6d4;\">Docs</a> •\n",
        "  <a href=\"/\" style=\"color: #06b6d4;\">Templates</a> •\n",
        "  <a href=\"https://discord.gg/NVDyv7TUgJ\" style=\"color: #06b6d4;\">Discord</a>\n",
        "</center>\n",
        "\n",
        "# Fine-tuning Mixtral 8x7B using QLoRA 🤙\n",
        "\n",
        "Welcome!\n",
        "\n",
        "In this notebook and tutorial, we will fine-tune the [Mixtral 8x7B](https://huggingface.co/mistralai/Mixtral-8x7B-v0.1) Mixture of Experts (MoE) model, which outperforms Llama 2 70B on most tested benchmarks.\n",
        "\n",
        "**Watch an accompanying video walk-through (but for Mistral 7B) [here](https://youtu.be/kmkcNVvEz-k?si=Ogt1wRFNqYI6zXfw&t=1)!** If you'd like to see that notebook instead, click [here](https://github.com/brevdev/notebooks/blob/main/mistral-finetune-own-data.ipynb).\n",
        "\n",
        "[![](https://uohmivykqgnnbiouffke.supabase.co/storage/v1/object/public/landingpage/youtubebadge.svg)](https://www.youtube.com/watch?v=kmkcNVvEz-k&t=1s)\n",
        "\n",
        "This tutorial will use QLoRA, a fine-tuning method that combines quantization and LoRA. For more information about what those are and how they work, see [this post](https://developer.nvidia.com/brev/blog/how-qlora-works).\n",
        "\n",
        "In this notebook, we will load the large model in 4bit using `bitsandbytes` and use LoRA to train using the PEFT library from Hugging Face 🤗.\n",
        "\n",
        "Note that if you ever have trouble importing something from Huggingface, you may need to run `huggingface-cli login` in a shell. To open a shell in Jupyter Lab, click on 'Launcher' (or the '+' if it's not there) next to the notebook tab at the top of the screen. Under \"Other\", click \"Terminal\" and then run the command.\n",
        "\n",
        "### Help us make this tutorial better! Please provide feedback on the [Discord channel](https://discord.gg/y9428NwTh3) or on [X](https://x.com/harperscarroll)."
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "SSBw-KpkyRga"
      },
      "source": [
        "#### Before we begin: A note on OOM errors\n",
        "\n",
        "If you get an error like this: `OutOfMemoryError: CUDA out of memory`, tweak your parameters to make the model less computationally intensive. I will help guide you through that in this guide, and if you have any additional questions you can reach out on the [Discord channel](https://discord.gg/y9428NwTh3) or on [X](https://x.com/harperscarroll).\n",
        "\n",
        "To re-try after you tweak your parameters, open a Terminal ('Launcher' or '+' in the nav bar above -> Other -> Terminal) and run the command `nvidia-smi`. Then find the process ID `PID` under `Processes` and run the command `kill [PID]`. You will need to re-start your notebook from the beginning. (There may be a better way to do this... if so please do let me know!)"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "VC-9m2yv3m18"
      },
      "source": [
        "## Let's begin!\n",
        "### 0. Preparing data\n",
        "\n",
        "Before you check out a GPU, prepare your dataset for loading and training.\n",
        "\n",
        "To prepare your dataset for loading, all you need are two `.jsonl` files structured something like this:\n",
        "```\n",
        "{\"input\": \"What color is the sky?\", \"output\": \"The sky is blue.\"}\n",
        "{\"input\": \"Where is the best place to get cloud GPUs?\", \"output\": \"Brev\"}\n",
        "```\n",
        "If you choose to model your data as input/output pairs, you'll want to use something like the second `formatting_func` below, which will will combine all your features into one input string.\n",
        "\n",
        "As you can see below, I have `notes.jsonl` for my `train_dataset` and `notes_validation.jsonl` for my `eval_dataset`.\n",
        "\n",
        "I used Exporter, a free local-only app, to export my Apple Notes to `.txt` files, and then I wrote a script to process each note into one `.jsonl` file. Note that for this script, ChatGPT can help out a LOT if you tell it how your data is currently formatted, how you'd like it to be formatted, and ask it to write a script in a certain language you know well (for any debugging) to do so. I also broke up my journal entries so the training sample vector length was smaller (see the discussion on `max_length` and the data visualization below). I broke it into pieces so that contexts were encapsulated entirely, since I did want the model to understand context about my life. My data were ultimately formatted as:\n",
        "\n",
        "```json\n",
        "{\"note\": \"journal-entry-for-model-to-predict\"}\n",
        "{\"note\": \"journal-entry-for-model-to-predict-1\"}\n",
        "{\"note\": \"journal-entry-for-model-to-predict-2\"}\n",
        "```"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "E2CkxsA43m15"
      },
      "source": [
        "### 1. Instantiate GPU & Load Dataset\n",
        "\n",
        "I used a GPU and dev environment from [brev.dev](https://developer.nvidia.com/brev). Click the badge below to get your preconfigured instance:\n",
        "\n",
        "[![](https://brev-assets.s3.us-west-1.amazonaws.com/nv-lb-dark.svg)](https://brev.nvidia.com/environment/new?instance=T4:g4dn.12xlarge&diskStorage=512&name=mixtral-finetune-own-data&file=https://github.com/brevdev/notebooks/raw/main/mixtral-finetune-own-data.ipynb&python=3.10&cuda=12.0.1)\n",
        "\n",
        "A 4xT4 (as linked) with 16 GPU Memory per GPU was enough for me. At the time of writing this, it costs $3.91/hour, and it trained for about 4 hours for 300 training steps. You may need more GPUs and/or Memory if your sequence max_length is larger than 512.\n",
        "\n",
        "Once you've checked out your machine and landed in your instance page, select the specs you'd like (I used **Python 3.10 and CUDA 12.0.1**; these should be preconfigured for you if you use the badge above) and click the \"Build\" button to build your verb container. Give this a few minutes.\n",
        "\n",
        "A few minutes after your model has started Running, click the 'Notebook' button on the top right of your screen once it illuminates (you may need to refresh the screen). You will be taken to a Jupyter Lab environment, where you can upload this Notebook.\n",
        "\n",
        "\n",
        "Note: You can connect your cloud credits (AWS or GCP) by clicking \"Org: \" on the top right, and in the panel that slides over, click \"Connect AWS\" or \"Connect GCP\" under \"Connect your cloud\" and follow the instructions linked to attach your credentials."
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "#### Install the necessary packages"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "scrolled": true
      },
      "outputs": [],
      "source": [
        "!pip install bitsandbytes\n",
        "!pip install transformers\n",
        "!pip install peft\n",
        "!pip install accelerate\n",
        "!pip install datasets scipy ipywidgets matplotlib"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "-9KNTJZkyRgn"
      },
      "source": [
        "#### Weights & Biases for tracking metrics\n",
        "\n",
        "Let's use Weights & Biases to track our training metrics. You'll need to apply an API key when prompted. Feel free to skip this if you'd like, and just comment out the `wandb` parameters in the `Trainer` definition below."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "DDqUNyIoyRgo"
      },
      "outputs": [],
      "source": [
        "!pip install -q wandb -U\n",
        "\n",
        "import wandb, os\n",
        "wandb.login()\n",
        "\n",
        "wandb_project = \"viggo-finetune\"\n",
        "if len(wandb_project) > 0:\n",
        "    os.environ[\"WANDB_PROJECT\"] = wandb_project"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "#### Load the dataset"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "s6f4z8EYmcJ6"
      },
      "outputs": [],
      "source": [
        "from datasets import load_dataset\n",
        "\n",
        "train_dataset = load_dataset('json', data_files='notes.jsonl', split='train')\n",
        "eval_dataset = load_dataset('json', data_files='notes_validation.jsonl', split='train')"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "uhw8JiOr3m18"
      },
      "source": [
        "#### Formatting prompts\n",
        "Then create a `formatting_func` to structure training examples as prompts."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "f-fJR0MlQiTD"
      },
      "outputs": [],
      "source": [
        "def formatting_func(example):\n",
        "    text = f\"### The following is a note by Eevee the Dog: {example['note']}\"\n",
        "    return text"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "sflV0DL2P64_"
      },
      "source": [
        "Here's another common one:\n",
        "\n",
        "```python\n",
        "def formatting_func(example):\n",
        "    text = f\"### Question: {example['input']}\\n ### Answer: {example['output']}\"\n",
        "    return text\n",
        "```"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "shz8Xdv-yRgf"
      },
      "source": [
        "### 2. Load Base Model"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "MJ-5idQwzvg-"
      },
      "source": [
        "Let's now load Mixtral using 4-bit quantization!"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "from huggingface_hub import notebook_login\n",
        "\n",
        "notebook_login()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "!nvidia-smi"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "referenced_widgets": [
            "45524c98039a46d5b7745ad7cb638d2f"
          ]
        },
        "id": "E0Nl5mWL0k2T",
        "outputId": "47b6b01d-e9f2-4b70-919c-17ae64993843"
      },
      "outputs": [],
      "source": [
        "import torch\n",
        "from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig\n",
        "\n",
        "base_model_id = \"mistralai/Mixtral-8x7B-v0.1\"\n",
        "bnb_config = BitsAndBytesConfig(\n",
        "    load_in_4bit=True,\n",
        "    bnb_4bit_use_double_quant=True,\n",
        "    bnb_4bit_compute_dtype=torch.bfloat16\n",
        ")\n",
        "\n",
        "model = AutoModelForCausalLM.from_pretrained(base_model_id, quantization_config=bnb_config, device_map=\"auto\")"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "UjNdXolqyRgf"
      },
      "source": [
        "### 3. Tokenization\n",
        "\n",
        "Set up the tokenizer. Add padding on the left as it [makes training use less memory](https://ai.stackexchange.com/questions/41485/while-fine-tuning-a-decoder-only-llm-like-llama-on-chat-dataset-what-kind-of-pa).\n",
        "\n",
        "\n",
        "For `model_max_length`, it's helpful to get a distribution of your data lengths. Let's first tokenize without the truncation/padding, so we can get a length distribution."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "haSUDD9HyRgf",
        "outputId": "22ee95db-2974-4ab0-e0c7-444d04d3e838"
      },
      "outputs": [],
      "source": [
        "tokenizer = AutoTokenizer.from_pretrained(\n",
        "    base_model_id,\n",
        "    padding_side=\"left\",\n",
        "    add_eos_token=True,\n",
        "    add_bos_token=True,\n",
        ")\n",
        "tokenizer.pad_token = tokenizer.eos_token\n",
        "\n",
        "def generate_and_tokenize_prompt(prompt):\n",
        "    return tokenizer(formatting_func(prompt))"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "WHnKLcq4yRgg"
      },
      "source": [
        "Reformat the prompt and tokenize each sample:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "S3iLAwLh3m19"
      },
      "outputs": [],
      "source": [
        "tokenized_train_dataset = train_dataset.map(generate_and_tokenize_prompt)\n",
        "tokenized_val_dataset = eval_dataset.map(generate_and_tokenize_prompt)"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "O6ewk27p3m19"
      },
      "source": [
        "Let's get a distribution of our dataset lengths, so we can determine the appropriate `max_length` for our input tensors."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "BA8M9yfC3m19",
        "outputId": "99c6d302-9bb6-47b1-cae9-a1cd870b4770"
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\n",
        "\n",
        "def plot_data_lengths(tokenized_train_dataset, tokenized_val_dataset):\n",
        "    lengths = [len(x['input_ids']) for x in tokenized_train_dataset]\n",
        "    lengths += [len(x['input_ids']) for x in tokenized_val_dataset]\n",
        "    print(len(lengths))\n",
        "\n",
        "    # Plotting the histogram\n",
        "    plt.figure(figsize=(10, 6))\n",
        "    plt.hist(lengths, bins=20, alpha=0.7, color='blue')\n",
        "    plt.xlabel('Length of input_ids')\n",
        "    plt.ylabel('Frequency')\n",
        "    plt.title('Distribution of Lengths of input_ids')\n",
        "    plt.show()\n",
        "\n",
        "plot_data_lengths(tokenized_train_dataset, tokenized_val_dataset)"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "nBk4Qp_vyRgh"
      },
      "source": [
        "From here, you can choose where you'd like to set the `max_length` to be. You can truncate and pad training examples to fit them to your chosen size. Be aware that choosing a larger `max_length` has its compute tradeoffs.\n",
        "\n",
        "I'm using my personal notes to train the model, and they vary greatly in length. I spent some time cleaning the dataset so the samples were about the same length, cutting up individual notes if needed, but being sure to not cut in the middle of a word or sentence."
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "bMlw8h743m19"
      },
      "source": [
        "Now let's tokenize again with padding and truncation, and set up the tokenize function to make labels and input_ids the same. This is basically what [self-supervised fine-tuning is](https://neptune.ai/blog/self-supervised-learning)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "acINaViR3m19"
      },
      "outputs": [],
      "source": [
        "max_length = 512 # This was an appropriate max length for my dataset\n",
        "\n",
        "def generate_and_tokenize_prompt2(prompt):\n",
        "    result = tokenizer(\n",
        "        formatting_func(prompt),\n",
        "        truncation=True,\n",
        "        max_length=max_length,\n",
        "        padding=\"max_length\",\n",
        "    )\n",
        "    result[\"labels\"] = result[\"input_ids\"].copy()\n",
        "    return result"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "referenced_widgets": [
            "518d4f0b89bf4d57bf00d4c6d6e59eb5"
          ]
        },
        "id": "lTk-aTog3m19",
        "outputId": "4fb637b4-77a2-47c6-de7b-4fb620663dd7"
      },
      "outputs": [],
      "source": [
        "tokenized_train_dataset = train_dataset.map(generate_and_tokenize_prompt2)\n",
        "tokenized_val_dataset = eval_dataset.map(generate_and_tokenize_prompt2)"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "TQL796OayRgh"
      },
      "source": [
        "Check that `input_ids` is padded on the left with the `eos_token` (2) and there is an `eos_token` 2 added to the end, and the prompt starts with a `bos_token` (1)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "OKHhvxK83m19"
      },
      "outputs": [],
      "source": [
        "print(tokenized_train_dataset[1]['input_ids'])"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "I6LRa2Zm3m19"
      },
      "source": [
        "Now all the samples should be the same length, `max_length`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "I55Yo3yy3m19",
        "outputId": "c87e344d-e0f3-4542-afcc-4e2025926d64"
      },
      "outputs": [],
      "source": [
        "plot_data_lengths(tokenized_train_dataset, tokenized_val_dataset)"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "jP3R4enP3m19"
      },
      "source": [
        "### How does the base model do?"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "Vxbl4ACsyRgi"
      },
      "source": [
        "Optionally, you can check how Mixtral does on one of your data samples. For example, if you have a dataset of users' biometric data to their health scores, you could test the following `eval_prompt`:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "gOxnx-cAyRgi"
      },
      "outputs": [],
      "source": [
        "eval_prompt = \"\"\" Given the following biometric data, score the users' health, from 0-100.\n",
        "\n",
        "### Biometric Data:\n",
        "Temperature=98.2,\n",
        "Sex=F,\n",
        "Age=29,\n",
        "Height=69 inches,\n",
        "Weight=160 lbs,\n",
        "V02_Max=55,\n",
        "HRV=55\n",
        "\n",
        "### Health Score:\n",
        "\"\"\""
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "KRhfq_Fa3m19"
      },
      "source": [
        "The `eval_prompt` I used was:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "pa6ux9ni3m19"
      },
      "outputs": [],
      "source": [
        "eval_prompt = \" The following is a note by Eevee the Dog, that doesn't share anything too personal: # \""
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "NidIuFXMyRgi",
        "outputId": "b1794b11-9a22-4b0a-e871-7df039ab59fc"
      },
      "outputs": [],
      "source": [
        "# Re-init the tokenizer so it doesn't add padding or eos token\n",
        "tokenizer = AutoTokenizer.from_pretrained(\n",
        "    base_model_id,\n",
        "    add_bos_token=True,\n",
        ")\n",
        "\n",
        "model_input = tokenizer(eval_prompt, return_tensors=\"pt\").to(\"cuda\")\n",
        "\n",
        "model.eval()\n",
        "with torch.no_grad():\n",
        "    print(tokenizer.decode(model.generate(**model_input, max_new_tokens=150, repetition_penalty=1.15)[0], skip_special_tokens=True))"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "dCAWeCzZyRgi"
      },
      "source": [
        "Observe how the model does out of the box. It doesn't talk like me. "
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "AapDoyfAyRgi"
      },
      "source": [
        "### 4. Set Up LoRA"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "Mp2gMi1ZzGET"
      },
      "source": [
        "Now, to start our fine-tuning, we have to apply some preprocessing to the model to prepare it for training. For that use the `prepare_model_for_kbit_training` method from PEFT."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "a9EUEDAl0ss3"
      },
      "outputs": [],
      "source": [
        "from peft import prepare_model_for_kbit_training\n",
        "\n",
        "model.gradient_checkpointing_enable()\n",
        "model = prepare_model_for_kbit_training(model)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "gkIcwsSU01EB"
      },
      "outputs": [],
      "source": [
        "def print_trainable_parameters(model):\n",
        "    \"\"\"\n",
        "    Prints the number of trainable parameters in the model.\n",
        "    \"\"\"\n",
        "    trainable_params = 0\n",
        "    all_param = 0\n",
        "    for _, param in model.named_parameters():\n",
        "        all_param += param.numel()\n",
        "        if param.requires_grad:\n",
        "            trainable_params += param.numel()\n",
        "    print(\n",
        "        f\"trainable params: {trainable_params} || all params: {all_param} || trainable%: {100 * trainable_params / all_param}\"\n",
        "    )"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "cUYEpEK-yRgj"
      },
      "source": [
        "Let's print the model to examine its layers, as we will apply QLoRA to all the linear layers of the model. Those layers are `q_proj`, `k_proj`, `v_proj`, `o_proj`, `w1`, `w2`, `w3`, and `lm_head`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "XshGNsbxyRgj",
        "outputId": "c619b0e8-8516-4d4b-9abe-13eaa3f3b204",
        "scrolled": true
      },
      "outputs": [],
      "source": [
        "print(model)"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "I6mTLuQJyRgj"
      },
      "source": [
        "Here we define the LoRA config.\n",
        "\n",
        "`r` is the rank of the low-rank matrix used in the adapters, which thus controls the number of parameters trained. A higher rank will allow for more expressivity, but there is a compute tradeoff.\n",
        "\n",
        "`alpha` is the scaling factor for the learned weights. The weight matrix is scaled by `alpha/r`, and thus a higher value for `alpha` assigns more weight to the LoRA activations.\n",
        "\n",
        "The values used in the QLoRA paper were `r=64` and `lora_alpha=16`, and these are said to generalize well, but we will use `r=32` and `lora_alpha=64` so that we have more emphasis on the new fine-tuned data while also reducing computational complexity."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Ybeyl20n3dYH",
        "outputId": "6a16c182-04d9-4812-ae81-502a8fe364d0"
      },
      "outputs": [],
      "source": [
        "from peft import LoraConfig, get_peft_model\n",
        "\n",
        "config = LoraConfig(\n",
        "    r=32,\n",
        "    lora_alpha=64,\n",
        "    target_modules=[\n",
        "        \"q_proj\",\n",
        "        \"k_proj\",\n",
        "        \"v_proj\",\n",
        "        \"o_proj\",\n",
        "        \"w1\",\n",
        "        \"w2\",\n",
        "        \"w3\",\n",
        "        \"lm_head\",\n",
        "    ],\n",
        "    bias=\"none\",\n",
        "    lora_dropout=0.05,  # Conventional\n",
        "    task_type=\"CAUSAL_LM\",\n",
        ")\n",
        "\n",
        "model = get_peft_model(model, config)\n",
        "print_trainable_parameters(model)"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "X_FHi_VLyRgn"
      },
      "source": [
        "See how the model looks different now, with the LoRA adapters added:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "IaYMWak4yRgn"
      },
      "outputs": [],
      "source": [
        "print(model)"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "_0MOtwf3zdZp"
      },
      "source": [
        "### 5. Run Training!"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "fEe0uWYSyRgo"
      },
      "source": [
        "I didn't have a lot of training samples: only about 200 total train/validation. I used 300 training steps, and I was fine with overfitting in this case. I found that the end product worked well. It took about two hours on the 4xT4.\n",
        "\n",
        "Overfitting is when the validation loss goes up (bad) while the training loss goes down significantly, meaning the model is learning the training set really well, but is unable to generalize to new datapoints. In most cases, this is not desired, but since I am just playing around with a model to generate outputs like my journal entries, I was fine with a moderate amount of overfitting.\n",
        "\n",
        "With that said, a note on training: you can set the `max_steps` to be high initially, and examine at what step your model's performance starts to degrade. There is where you'll find a sweet spot for how many steps to perform. For example, say you start with 1000 steps, and find that at around 250 steps the model starts overfitting, as described above. Therefore, 500 steps would be your sweet spot, so you would use the `checkpoint-250` model repo in your output dir (`mixtral-journal-finetune`) as your final model in step 6 below.\n",
        "\n",
        "If you're just doing something for fun like I did and are OK with overfitting, you can try different checkpoint versions with different degrees of overfitting.\n",
        "\n",
        "You can interrupt the process via Kernel -> Interrupt Kernel in the top nav bar once you realize you didn't need to train anymore."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "tokenizer = AutoTokenizer.from_pretrained(\n",
        "    base_model_id,\n",
        "    padding_side=\"left\",\n",
        "    add_eos_token=True,\n",
        "    add_bos_token=True,\n",
        ")\n",
        "tokenizer.pad_token = tokenizer.eos_token"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "c_L1131GyRgo"
      },
      "outputs": [],
      "source": [
        "if torch.cuda.device_count() > 1: # If more than 1 GPU\n",
        "    model.is_parallelizable = True\n",
        "    model.model_parallel = True"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "jq0nX33BmfaC"
      },
      "outputs": [],
      "source": [
        "import transformers\n",
        "from datetime import datetime\n",
        "\n",
        "project = \"journal-finetune\"\n",
        "base_model_name = \"mixtral\"\n",
        "run_name = base_model_name + \"-\" + project\n",
        "output_dir = \"./\" + run_name\n",
        "\n",
        "trainer = transformers.Trainer(\n",
        "    model=model,\n",
        "    train_dataset=tokenized_train_dataset,\n",
        "    eval_dataset=tokenized_val_dataset,\n",
        "    args=transformers.TrainingArguments(\n",
        "        output_dir=output_dir,\n",
        "        warmup_steps=1,\n",
        "        per_device_train_batch_size=2,\n",
        "        gradient_accumulation_steps=1,\n",
        "        gradient_checkpointing=True,\n",
        "        max_steps=300,\n",
        "        learning_rate=2.5e-5, # Want a small lr for finetuning\n",
        "        fp16=True, \n",
        "        optim=\"paged_adamw_8bit\",\n",
        "        logging_steps=25,              # When to start reporting loss\n",
        "        logging_dir=\"./logs\",        # Directory for storing logs\n",
        "        save_strategy=\"steps\",       # Save the model checkpoint every logging step\n",
        "        save_steps=25,                # Save checkpoints every 50 steps\n",
        "        evaluation_strategy=\"steps\", # Evaluate the model every logging step\n",
        "        eval_steps=25,               # Evaluate and save checkpoints every 50 steps\n",
        "        do_eval=True,                # Perform evaluation at the end of training\n",
        "        report_to=\"wandb\",           # Comment this out if you don't want to use weights & baises\n",
        "        run_name=f\"{run_name}-{datetime.now().strftime('%Y-%m-%d-%H-%M')}\"          # Name of the W&B run (optional)\n",
        "    ),\n",
        "    data_collator=transformers.DataCollatorForLanguageModeling(tokenizer, mlm=False),\n",
        ")\n",
        "\n",
        "model.config.use_cache = False  # silence the warnings. Please re-enable for inference!\n",
        "trainer.train()"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "R9rRmDCeQiTJ"
      },
      "source": [
        "I cleared the output of the cell above because I stopped the training early, and it produced a long, ugly error message."
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "0D57XqcsyRgo"
      },
      "source": [
        "### 6. Drum Roll... Try the Trained Model!\n",
        "\n",
        "It's a good idea to kill the current process so that you don't run out of memory loading the base model again on top of the model we just trained. Go to `Kernel > Restart Kernel` or kill the process via the Terminal (`nvidia smi` > `kill [PID]`). \n",
        "\n",
        "By default, the PEFT library will only save the QLoRA adapters, so we need to first load the base model from the Huggingface Hub:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "referenced_widgets": [
            "fb8230fb86884aa6be318e2d03a88af2"
          ]
        },
        "id": "SKSnF016yRgp",
        "outputId": "bce5209d-90da-4117-c6ac-cda9f3cb3422",
        "scrolled": true
      },
      "outputs": [],
      "source": [
        "import torch\n",
        "from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig\n",
        "\n",
        "base_model_id = \"mistralai/Mixtral-8x7B-v0.1\"\n",
        "bnb_config = BitsAndBytesConfig(\n",
        "    load_in_4bit=True,\n",
        "    bnb_4bit_use_double_quant=True,\n",
        "    bnb_4bit_compute_dtype=torch.bfloat16\n",
        ")\n",
        "\n",
        "base_model = AutoModelForCausalLM.from_pretrained(\n",
        "    base_model_id,\n",
        "    quantization_config=bnb_config,\n",
        "    device_map=\"auto\",\n",
        "    trust_remote_code=True,\n",
        "    use_auth_token=True\n",
        ")\n",
        "\n",
        "tokenizer = AutoTokenizer.from_pretrained(base_model_id, add_bos_token=True, trust_remote_code=True)"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "_BxOhAiqyRgp"
      },
      "source": [
        "Now load the QLoRA adapter from the appropriate checkpoint directory, i.e. the best performing model checkpoint:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "GwsiqhWuyRgp"
      },
      "outputs": [],
      "source": [
        "from peft import PeftModel\n",
        "\n",
        "ft_model = PeftModel.from_pretrained(base_model, \"mixtral-journal-finetune/checkpoint-275\")"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "lX39ibolyRgp"
      },
      "source": [
        "and run your inference!"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "UUehsaVNyRgp"
      },
      "source": [
        "Let's try the same `eval_prompt` and thus `model_input` as above, and see if the new finetuned model performs better. I like playing with the repetition penalty (just little tweaks of .01-.05 at a time). THIS IS SO FUN."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "lMkVNEUvyRgp",
        "outputId": "7d49d409-5dbe-4306-c1a4-9d87e3073397"
      },
      "outputs": [],
      "source": [
        "eval_prompt = \" The following is a note by Eevee the Dog, that doesn't share anything too personal: # \"\n",
        "model_input = tokenizer(eval_prompt, return_tensors=\"pt\").to(\"cuda\")\n",
        "\n",
        "ft_model.eval()\n",
        "with torch.no_grad():\n",
        "    print(tokenizer.decode(ft_model.generate(**model_input, max_new_tokens=150, repetition_penalty=1.15)[0], skip_special_tokens=True))"
      ]
    },
    {
      "attachments": {},
      "cell_type": "markdown",
      "metadata": {
        "id": "VCJnpZoayRgq"
      },
      "source": [
        "### Sweet... it worked! The fine-tuned model now prints out journal entries in my style!\n",
        "\n",
        "How funny to see it write like me as an angsty teenager, and honestly adult. I am obsessed. It knows who my friends are and talks about them, and covers the same topics I usually cover. It's really cool.\n",
        "\n",
        "That output is quite private but I wanted you to see an example run, so I tweaked the `eval_prompt` so that it explicitly wouldn't say anything too sensitive, haha. \n",
        "\n",
        "I hope you enjoyed this tutorial on fine-tuning Mistral's MoE (\"Mixtral\") on your own data. If you have any questions, feel free to reach out to me on [X](https://x.com/harperscarroll) or [Discord](https://discord.gg/RN2a436M73).\n",
        "\n",
        "🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙 🤙"
      ]
    }
  ],
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "gpuType": "T4",
      "provenance": []
    },
    "gpuClass": "standard",
    "kernelspec": {
      "display_name": "Python 3 (ipykernel)",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.10.12"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 4
}
